﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.BusinessLogical.DAL;
using CarolLib;
using DispatchAssist.BusinessLogical.Model;
using System.Collections;
using DispatchAssist.Model;

namespace DispatchAssist.BusinessLogical.BLL
{
    public class FlightInfoManager
    {
        #region Members

        private IDataProvider _provider;
        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static readonly FlightInfoManager Instance = new FlightInfoManager();

        #endregion

        public FlightInfoManager()
        {
            _provider = new SqlDataProvider();
        }

        #region Method Body

        public int DetectUpdateFlightBackUpInfo(List<FlightInfo> flightInfos)
        {
            int count = 0;
            foreach (var item in flightInfos)
            {
                try
                {
                    if (_provider.UpdateFlightBackUpInfo(item))
                    {
                        //CacheHelper.Remove(ALlFlightInfoCacheKey); 


                        //补充生成预警信息
                        DetectAndCreateALertInfo(item);


                        count++;
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("FlightInfoManager. UpdateFlightBackUpInfo() " + e.Message);
                }
            }

            return count;


        }

        public void DetectAndCreateALertInfo(FlightInfo flightInfo)
        {
            List<MeteoMsg> mtMsgList = null;
            try
            {
                 mtMsgList = GetMeteoMsgByFlightInfo(flightInfo);
            }
            catch (Exception e)
            {
                Logger.Error(e);
                return;
            }

            foreach (MeteoMsg mtMsg in mtMsgList)
            {
                Alert alertInfo = new Alert();
                alertInfo.MetroMsgID = mtMsg.MetroMsgID;
                alertInfo.FlightInfoID = flightInfo.FlightInfoID;
                alertInfo.AlertTime = mtMsg.WarnTime;
                alertInfo.AirportRelation = ((Enums.AirPortRelationType)mtMsg.RelationType).ToString();

                try
                {
                    alertInfo.AlertActionFlag = CommonCacheData.CacheAR.GetActionFlag(mtMsg.Airport, mtMsg.WarnLevel);
                    alertInfo.SeatID = CommonCacheData.CacheST.GetSeatID(flightInfo.TailNo);
                }
                catch (Exception e)
                {
                    Logger.Error("get cache data error", e);
                    continue;
                }

                alertInfo.PerformActionFlag = 0;


                alertInfo.LastModifyTime = DateTime.Now;
                alertInfo.DeleteFlag = false;

                
                try
                {
                    new CreateAlertMsgManager().InsertAlertModel(alertInfo);
                }
                catch (Exception e)
                {
                    Logger.Error(string.Format("error in InsertAlertModel FlightInfoID is {0},MeteoMsgID is {1}",flightInfo.FlightInfoID,mtMsg.MetroMsgID),e);
                    continue;
                }
            }
        }

        public List<FlightInfo> GetFlightInfoByPara(string carrier, string flightNo, DateTime planDeptTime, string deptAirport, int flag)
        {
            return _provider.GetFlightInfoByPara(carrier, flightNo, planDeptTime, deptAirport, flag);
        }

        public List<MeteoMsg> GetMeteoMsgByFlightInfo(FlightInfo flightInfo)
        {
            List<MeteoMsg> meteoMsgList = new List<MeteoMsg>();
           
            DateTime? deptTime = GetDeptTimeByCondition(flightInfo.RealDeptTime, flightInfo.EstDeptTime, flightInfo.PlanDeptTime);

            List<AirPortType> backAirportList = GetBackupInfosByFlightInfo(flightInfo);

            foreach (AirPortType backAirport in backAirportList)
            {
                List<MeteoMsg> list = _provider.GetMeteoMsgListByPara(backAirport.Type, backAirport.Airport, deptTime==null?deptTime:deptTime.Value.AddHours(CommonCacheData.CacheET.GetEarlyTime(backAirport.Airport)*-1));

                meteoMsgList.AddRange(list);
            }

            return meteoMsgList;
        }

        private List<AirPortType> GetBackupInfosByFlightInfo(FlightInfo flightInfo)
        {
            List<AirPortType> result = new List<AirPortType>();

            if (!string.IsNullOrEmpty(flightInfo.DeptBackup))
            {
                string[] airports = flightInfo.DeptBackup.Split('|');

                foreach (string airport in airports)
                {
                    AirPortType info = new AirPortType();

                    info.Airport = airport;
                    info.Type = (int)Enums.AirPortRelationType.起飞备降场;
                    result.Add(info);
                }
               // result.Add((int)Enums.AirPortRelationType.起飞备降场, flightInfo.DeptBackup);
            }
            if (!string.IsNullOrEmpty(flightInfo.ArrBackup))
            {
                string[] airports = flightInfo.ArrBackup.Split('|');

                foreach (string airport in airports)
                {
                    AirPortType info = new AirPortType();

                    info.Airport = airport;
                    info.Type = (int)Enums.AirPortRelationType.降落备降场;
                    result.Add(info);
                }
                //result.Add((int)Enums.AirPortRelationType.降落备降场,flightInfo.ArrBackup);
            }
            if (!string.IsNullOrEmpty(flightInfo.RouteBackup))
            {
                string[] airports = flightInfo.RouteBackup.Split('|');

                foreach (string airport in airports)
                {
                    AirPortType info = new AirPortType();

                    info.Airport = airport;
                    info.Type = (int)Enums.AirPortRelationType.航路备降场;
                    result.Add(info);
                }

                //result.Add((int)Enums.AirPortRelationType.航路备降场, flightInfo.RouteBackup);
            }

            return result;
        }

        private DateTime? GetDeptTimeByCondition(DateTime? realDeptTime, DateTime? estDeptTime, DateTime planDeptTime)
        {
            DateTime? dt = null;
            if (realDeptTime != null)
            {
                dt = null;
            }
            else if (estDeptTime != null) { dt = estDeptTime; }
            else { dt = planDeptTime; }
            return dt;// == null ? new DateTime() : Convert.ToDateTime(dt);
        }

        #endregion

    }
}
